---
title: "LangChain.js"
description: "Integrate LangChain JS chains as backend actions in your CopilotKit application."
icon: "custom/langchain"
---
import FindCopilotRuntimeSnippet from "@/snippets/find-your-copilot-runtime.mdx";

<Steps>
<Step>
<FindCopilotRuntimeSnippet />
</Step>

<Step>
### Integrate LangChain JS actions with CopilotRuntime

CopilotKit allows actions to return not only values but also LangChain streams. This means you can call LangChain chains directly and return their streams as part of your backend actions. Here's how to implement LangChain JS backend actions:

<Callout>
**Note** that `actions` is not merely an array of actions, but an array **generator**.
This generator takes `properties` and `url` as input.

This means you can **customize which backend actions are made available** according to the current frontend URL, as well as custom properties you can pass from the frontend.
</Callout>


```tsx title="/api/copilotkit/route.ts"
import { ChatOpenAI } from "@langchain/openai";
import { ChatPromptTemplate } from "@langchain/core/prompts";

const runtime = new CopilotRuntime({
  // ... existing configuration
  actions: ({properties, url}) => {
    // Note that actions returns not an array, but an array **generator**.
    // You can use the input parameters to the actions generator to expose different backend actions to the Copilot at different times: 
    // `url` is the current URL on the frontend application.
    // `properties` contains custom properties you can pass from the frontend application.

    return [
      {
        name: "generateJokeForTopic",
        description: "Generates a joke for a given topic.",
        parameters: [
          {
            name: "topic",
            type: "string",
            description: "The topic to generate a joke about.",
            required: true,
          },
        ],
        handler: async ({topic}: {topic: string}) => {
          const prompt = ChatPromptTemplate.fromMessages([
            [
              "system",
              "You are a witty comedian. Generate a short, funny joke about the given topic. But make it sound like a pirate joke!",
            ],
            ["user", "Topic: {topic}"],
          ]);
          const chain = prompt.pipe(new ChatOpenAI());
          // [!code highlight:3]
          return chain.stream({ // return directly chain.stream
            topic: topic,
          });
        },
      },
    ]
  }
});

// ... rest of your route definition
```

</Step>

<Step>
### Test your implementation

After adding the LangChain JS action, test it by asking the copilot to generate a joke about a specific topic. Observe how it uses the LangChain components to generate and stream the response.
</Step>

</Steps>
